package cn.okcode.api.framework.interceptor;

import cn.okcode.api.framework.ActionContext;
import cn.okcode.api.framework.ActionInterceptor;
import cn.okcode.api.framework.Callee;
import com.alibaba.fastjson.JSON;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

/**
 * 日志拦截器
 *
 * @author pyk13
 */
public class ActionLogInterceptor implements ActionInterceptor {
    private long time;

    @Override
    public void beforeInvoke(ActionContext context) {
        time = System.currentTimeMillis();
        Callee callee = context.getCallee();
        Logger logger =  LogManager.getLogger(callee.getClazzName());
        if (logger.isDebugEnabled()) {
            logger.debug("BOPEditor:" + callee.getCallee() + ",startTime:" + time);
        }
    }

    @Override
    public void afterInvoke(ActionContext context) {
        Callee callee = context.getCallee();
        Logger logger = LogManager.getLogger(callee.getClazzName());
        long cost = System.currentTimeMillis() - time;
        if (logger.isDebugEnabled()) {
            logger.debug("BOPEditor:" + callee.getCallee() + ",cost time:" + cost);
        }
    }

    @Override
    public void onException(ActionContext context) {
        Callee callee = context.getCallee();
        Logger logger = LogManager.getLogger(callee.getClazzName());
        //跳骨windchill的类型
        String strParam = JSON.toJSONString(context.getParameters());
        long cost = System.currentTimeMillis() - time;
        if (logger.isDebugEnabled()) {
            logger.debug("BOPEditor:" + callee.getCallee() + ",cost time:" + cost);
        }
        logger.error("BOPEditor:---执行出错---参数---：");
        logger.error(strParam);
        logger.error("BOPEditor:", context.getThrowable());
    }
}
